import * as XLSX from "xlsx";
// import JsPDF from "jspdf";
import html2canvas from "html2canvas";

const excelData = (columns, dataSource) => {
	const titles = columns.map(item => item.title)
	const keys = columns.map(item => item.dataIndex)
	const dataList = dataSource.map(item => {
		return keys.map(key => item[key])
	})
	return [
		titles,
		...dataList
	]
}

export const exportData = (columns, dataSource, fileName) => {
	const data = excelData(columns, dataSource)
	const ws = XLSX.utils.aoa_to_sheet(data)
	const wb = XLSX.utils.book_new()
	XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
	XLSX.writeFile(wb, fileName)
}

// export const exportPdf = (elementId, exportName = 'export.pdf') => {
// 	const element = document.getElementById(elementId);
// 	html2canvas(element).then((canvas) => {
// 		const pdf = new JsPDF();
// 		//
// 		// // 将HTML元素转换为PDF
// 		// pdf.html(element, options);
// 		const canvasWidth = canvas.width;
// 		const canvasHeight = canvas.height;
// 		const pdfWidth = 210; // PDF页面宽度，单位为mm
// 		const pdfHeight = 297; // PDF页面高度，单位为mm
//
// 		const scale = Math.min(pdfWidth / canvasWidth, pdfHeight / canvasHeight);
// 		const scaledWidth = canvasWidth * scale;
// 		const scaledHeight = canvasHeight * scale;
// 		const imgData = canvas.toDataURL('image/png');
// 		pdf.addImage(imgData, 'PNG', 0, 5, scaledWidth, scaledHeight);
// 		// 保存PDF文件
// 		pdf.save(exportName)
// 	})
// }

export const printElement = (elementId) => {
	// const newStr = document.getElementById(elementId).innerHTML;
	let url = window.location.href;
	if (url.indexOf('?') > -1) {
		url += '&print=true';
	} else {
		url += '?print=true';
	}
	const printWindow = window.open(url, '_blank');
	printWindow.addEventListener('load', function() {
		setTimeout(() => {
			printWindow.document.body.innerHTML = printWindow.document.getElementById(elementId).innerHTML;
			if (printWindow.document.body.style.display === 'none') {
				printWindow.document.body.style.display = 'block';
			}
			printWindow.print();
			printWindow.close();
		}, 2000)
	});
}
